import pygame
import random

# 初始化pygame
pygame.init()

# 设置窗口大小和标题
size = width, height = 640, 480
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Avoid the Obstacles")

# 加载图片
player_image = pygame.image.load("player.png")
obstacle_image = pygame.image.load("obstacle.png")

# 设置玩家初始位置和速度
player_pos = [width / 2 - player_image.get_width() / 2, height - player_image.get_height()]
player_speed = [4, 4]

# 随机生成障碍物
obstacle_pos = [random.randint(0, width - obstacle_image.get_width()), -obstacle_image.get_height()]
obstacle_list = [obstacle_pos]

# 设置字体和分数
font = pygame.font.Font(None, 36)
score = 0

# 循环渲染窗口
while True:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                player_speed[0] = -4
            elif event.key == pygame.K_RIGHT:
                player_speed[0] = 4

    # 移动玩家
    player_pos[0] += player_speed[0]
    if player_pos[0] < 0:
        player_pos[0] = 0
    elif player_pos[0] > width - player_image.get_width():
        player_pos[0] = width - player_image.get_width()

    # 移动障碍物
    for idx, obstacle_pos in enumerate(obstacle_list):
        obstacle_pos[1] += 4

        # 移除已经超出屏幕的障碍物
        if obstacle_pos[1] > height:
            obstacle_list.pop(idx)
            score += 1

        # 检测是否发生碰撞
        if (obstacle_pos[1] + obstacle_image.get_height() > player_pos[1] and
                obstacle_pos[1] < player_pos[1] + player_image.get_height() and
                obstacle_pos[0] + obstacle_image.get_width() > player_pos[0] and
                obstacle_pos[0] < player_pos[0] + player_image.get_width()):
            pygame.quit()
            sys.exit()

    # 随机生成新的障碍物
    if random.randint(0, 100) < 10:
        obstacle_list.append([random.randint(0, width - obstacle_image.get_width()), -obstacle_image.get_height()])

    # 填充背景色
    screen.fill((255, 255, 255))

    # 绘制玩家和障碍物
    screen.blit(player_image, player_pos)
    for obstacle_pos in obstacle_list:
        screen.blit(obstacle_image, obstacle_pos)

    # 绘制分数
    score_text = font.render("Score: " + str(score), True, (0, 0, 0))
    screen.blit(score_text, [10, 10])

    # 刷新屏幕
    pygame.display.flip()